using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using QJY.API;
using QJY.Common;
using QJY.Data;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.SessionState;

namespace QJY.WEB
{
    /// <summary>
    /// WXAPI 的摘要说明
    /// </summary>
    public class WXAPI : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.AddHeader("Access-Control-Allow-Origin", "*");
            context.Response.AddHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE"); //支持的http 动作
            context.Response.AddHeader("Access-Control-Allow-Headers", "Accept, Origin, Content-type,authorization");
            context.Response.AddHeader("Access-Control-Allow-Credentials", "true");
            context.Response.AddHeader("pragma", "no-cache");
            context.Response.AddHeader("cache-control", "");
            context.Response.CacheControl = "no-cache";
            string strAction = context.Request["Action"] ?? "";
            Msg_Result Model = new Msg_Result() { Action = strAction.ToUpper(), ErrorMsg = "" };

            if (!string.IsNullOrEmpty(strAction))
            {
                #region 获取唯一code
                if (strAction.ToUpper() == "GetUserCodeByCode".ToUpper())
                {
                    #region 获取Code
                    Model.ErrorMsg = "获取Code错误，请重试";

                    string strCode = context.Request["code"] ?? "";
                    string strCorpID = context.Request["corpid"] ?? "";
                    string strModelCode = context.Request["funcode"] ?? "";

                    if (!string.IsNullOrEmpty(strCode))
                    {
                        var qy = new JH_Auth_QYB().GetEntity(p => p.corpId == strCorpID);
                        if (qy != null)
                        {
                            try
                            {
                                //通过微信接口获取用户名
                                WXHelp wx = new WXHelp(qy);
                                string username = wx.GetUserDataByCode(strCode, strModelCode);
                                if (!string.IsNullOrEmpty(username))
                                {
                                    var jau = new JH_Auth_UserB().GetUserByUserName(qy.ComId, username);
                                    if (jau != null)
                                    {
                                        //如果PCCode为空或者超过60分钟没操作,统统重新生成PCCode,并更新最新操作时间
                                        if (jau.logindate == null)
                                        {
                                            jau.logindate = DateTime.Now;
                                        }
                                        TimeSpan ts = new TimeSpan(jau.logindate.Value.Ticks).Subtract(new TimeSpan(DateTime.Now.Ticks)).Duration();
                                        if (string.IsNullOrEmpty(jau.pccode) || ts.TotalMinutes > 60)
                                        {
                                            string strGuid = JwtHelper.CreateJWT(KFDBActSet.ActNum,jau.UserName).Token;
                                            jau.pccode = strGuid;
                                            jau.logindate = DateTime.Now;
                                            new JH_Auth_UserB().Update(jau);
                                        }
                                        Model.ErrorMsg = "";
                                        Model.Result = jau.pccode;
                                        Model.Result1 = jau.UserName;
                                        Model.Result2 = ts.TotalMinutes;
                                        Model.Result3 = qy.FileServerUrl;
                                    }

                                }
                                else
                                {
                                    Model.ErrorMsg = "当前用户不存在";
                                }
                            }
                            catch (Exception ex)
                            {
                                Model.ErrorMsg = ex.ToString();
                            }
                        }
                        else
                        {
                            Model.ErrorMsg = "当前企业号未在电脑端注册";
                        }

                    }
                    else
                    {
                        Model.ErrorMsg = "Code为空";
                    }
                    #endregion
                }
                #endregion
                #region 是否存在
                if (strAction.ToUpper() == "isexist".ToUpper())
                {
                    if (context.Request["szhlcode"] != null)
                    {
                        //通过Cookies获取Code
                        //string szhlcode = "5ab470be-4988-4bb3-9658-050481b98fca"; 
                        string szhlcode = context.Request["szhlcode"].ToString();
                        //通过Code获取用户名，然后执行接口方法
                        var jau = new JH_Auth_UserB().GetUserByPCCode(szhlcode);
                        if (jau == null)
                        {
                            Model.Result = "NOCODE";
                        }
                    }
                }
                #endregion

                if (strAction.ToUpper() == "AUTOALERT")
                {
                    TXSXAPI.AUTOALERT();
                }

                if (strAction.ToUpper() == "BINDYH")//绑定用户
                {

                    string password = context.Request["password"] ?? "";
                    string username = context.Request["UserName"] ?? "";
                    string wxopenid = context.Request["wxopenid"] ?? "";
                    string nickname = context.Request["nickname"] ?? "";
                    string txurl = context.Request["txurl"] ?? "";


                    JH_Auth_QY qyModel = new JH_Auth_QYB().GetALLEntities().First();
                    password = CommonHelp.GetMD5(password);
                    JH_Auth_User userInfo = new JH_Auth_User();

                    List<JH_Auth_User> userList = new JH_Auth_UserB().GetEntities(d => (d.UserName == username || d.mobphone == username) && d.UserPass == password).ToList();
                    if (userList.Count() == 0)
                    {
                        Model.ErrorMsg = "用户名或密码不正确";
                    }
                    else
                    {
                        userInfo = userList[0];
                        if (userInfo.IsUse != "Y")
                        {
                            Model.ErrorMsg = "用户被禁用,请联系管理员";
                        }
                        if (Model.ErrorMsg == "")
                        {
                            userInfo.weixinCard = wxopenid;
                            userInfo.NickName = nickname;
                            userInfo.txurl = txurl;
                            new JH_Auth_UserB().Update(userInfo);
                            Model.Result = userInfo.pccode;
                            Model.Result1 = userInfo.UserName;
                            Model.Result2 = qyModel.FileServerUrl;
                            Model.Result4 = userInfo;
                        }

                    }
                }

                if (strAction.Equals("LOGIN",StringComparison.CurrentCultureIgnoreCase))
                {
                    StreamReader sr = new StreamReader(HttpContext.Current.Request.InputStream);
                    string responseStr = sr.ReadToEnd();
                    JObject JsonData = JObject.Parse(responseStr);
                    string corpnum = JsonData["corpnum"] == null ? "" : JsonData["corpnum"].ToString();
                    string username = JsonData["UserName"] == null ? "" : JsonData["UserName"].ToString();
                    string password = JsonData["password"] == null ? "" : JsonData["password"].ToString();
                    string chkcode = JsonData["chkcode"] == null ? "" : JsonData["chkcode"].ToString();
                    Model.ErrorMsg = "";

                    if (chkcode.ToUpper() != "APP")
                    {
                        if (context.Session["chkcode"] != null)
                        {
                            if (!chkcode.ToUpper().Equals(context.Session["chkcode"].ToString()))
                            {
                                Model.ErrorMsg = "验证码不正确";
                            }
                        }
                        else
                        {
                            Model.ErrorMsg = "验证码已过期";
                        }
                    }

                    #region 企业号确认数据中心
                    var objConString = new Kf.Center.DBInfo.PropsStr.PropsStr().GetActSetPropsStr(corpnum, 0);
                    if (string.IsNullOrWhiteSpace(objConString))
                    {
                        Model.ErrorMsg = @"当前企业号{corpnum}不存在";
                    }
                    else
                    {
                        KFDBActSet.ActNum = corpnum;
                        KFDBActSet.ActNum2ConString[corpnum] = objConString;
                        //WebHelper.WriteCookie("Kinfar_ADMS_ActNum", actnum);
                        if (username == "kfadmin")//验证自己表中用户
                        {
                            JH_Auth_QY qyModel = new JH_Auth_QYB().GetALLEntities().First();
                            password = CommonHelp.GetMD5(password);
                            JH_Auth_User userInfo = new JH_Auth_User();

                            List<JH_Auth_User> userList = new JH_Auth_UserB().GetEntities(d => (d.UserName == username || d.mobphone == username) && d.UserPass == password).ToList();
                            if (userList.Count() == 0)
                            {
                                Model.ErrorMsg = "用户名或密码不正确";
                            }
                            else
                            {
                                userInfo = userList[0];
                                if (userInfo.IsUse != "Y")
                                {
                                    Model.ErrorMsg = "用户被禁用,请联系管理员";
                                }
                                if (Model.ErrorMsg == "")
                                {
                                    string strToken = JwtHelper.CreateJWT(corpnum, username).Token;
                                    CacheHelp.Remove(username);//登陆时清理缓存
                                    Model.Result = strToken;
                                    Model.Result1 = userInfo.UserName;
                                    Model.Result2 = qyModel.FileServerUrl;
                                    Model.Result4 = userInfo;

                                    new JH_Auth_LogB().InsertLog("登录日志", context.Request.Path + "/" + Model.Action, JsonConvert.SerializeObject(Model), username, JsonConvert.SerializeObject(JsonData), 0, getIP(context));
                                }
                            }
                        }
                        else
                        {
                            #region 登录ERP验证
                            var DBMaster_Userid = "";
                            var openDoLogin = new Kf.Login.Login.OpenDoLogin();
                            //openDologin.OpenUserID = 2;
                            if(!Kf.Util.Constants.Login_Version.Equals(Kf.Util.Enum.SystemVersion.Single))
                                Kf.Util.Constants.Login_Version = Kf.Util.Enum.SystemVersion.Single;
                            bool isloginok = openDoLogin.DoLogin("", 0, 0, corpnum, username, password);
                            var orgusername = username;
                            if (isloginok)
                            {
                                username = $"{username}{corpnum}";
                                var eofUserRef = Kf.Core.EntityObjectFactory.GetInstanceNoException(openDoLogin.objContext, Kf.Util.EntityIDEnum.SysUserRel);
                                var eoUserRef = eofUserRef.FindFirst("SysUserID={0}", openDoLogin.objContext.UserID);
                                if (eoUserRef != null)
                                {
                                    DBMaster_Userid = eoUserRef.GetProperty("kfqjbiid").ToString();
                                }
                                else
                                {
                                    eoUserRef = eofUserRef.CreateObject();
                                    eoUserRef.SetProperty("SysUserID", openDoLogin.objContext.UserID);
                                }
                                //中台组织默认99999
                                //中台组织下的部门默认企业号
                                JH_Auth_User userInfo = null;
                                JH_Auth_QY qyModel = new JH_Auth_QYB().GetALLEntities().First();
                                if (string.IsNullOrWhiteSpace(DBMaster_Userid) || DBMaster_Userid.ToString()=="0")
                                {
                                    userInfo = new JH_Auth_User();
                                    #region 新增人员
                                    userInfo.UserName = username;
                                    userInfo.mobphone = username;
                                    userInfo.UserRealName = $"{orgusername}@{corpnum}";
                                    userInfo.UserPass = CommonHelp.GetMD5(password);
                                    userInfo.ComId = 10334;
                                    userInfo.BranchCode = 1;
                                    userInfo.CRDate = DateTime.Now;
                                    userInfo.CRUser = "kfadmin";
                                    userInfo.logindate = DateTime.Now;
                                    userInfo.IsUse = "Y";
                                    #endregion
                                    if (!new JH_Auth_UserB().Insert(userInfo))
                                    {
                                        Model.ErrorMsg = "添加用户失败";
                                    }
                                    else
                                    {
                                        //角色
                                        DBMaster_Userid=userInfo.ID.ToString();
                                        eoUserRef.SetProperty("kfqjbiid", DBMaster_Userid);
                                        eoUserRef.Context.SaveChanges();
                                        openDoLogin.objContext.Clear();
                                        openDoLogin = null;

                                        //为所有人增加普通员工的权限
                                        JH_Auth_Role rdefault = new JH_Auth_RoleB().GetEntity(p => p.ComId == userInfo.ComId && p.isSysRole == "Y" && p.RoleName == "普通用户");//找到默认角色
                                        if (rdefault != null)
                                        {
                                            JH_Auth_UserRole jaurdefault = new JH_Auth_UserRole();
                                            jaurdefault.ComId = userInfo.ComId;
                                            jaurdefault.RoleCode = rdefault.RoleCode;
                                            jaurdefault.UserName = userInfo.UserName;
                                            new JH_Auth_UserRoleB().Insert(jaurdefault);
                                            //}
                                        }
                                    }
                                }
                                else
                                {
                                    userInfo = new JH_Auth_UserB().GetEntities(d => (d.ID.ToString() == DBMaster_Userid)).FirstOrDefault();
                                    if (userInfo == null)
                                    {
                                        DBMaster_Userid = "";
                                        //角色
                                        eoUserRef.SetProperty("kfqjbiid", DBMaster_Userid);
                                        eoUserRef.Context.SaveChanges();
                                        openDoLogin.objContext.Clear();
                                        openDoLogin = null;
                                        //}
                                        Model.ErrorMsg = "关联用户不存在，请联系统管理员,在ERP取消关联";
                                    }
                                }
                                if (userInfo != null)
                                {
                                    if (userInfo.IsUse != "Y")
                                    {
                                        Model.ErrorMsg = "用户被禁用,请联系管理员";
                                    }
                                    if (Model.ErrorMsg == "")
                                    {
                                        string strToken = JwtHelper.CreateJWT(corpnum, username).Token;
                                        CacheHelp.Remove(username);//登陆时清理缓存
                                        Model.Result = strToken;
                                        Model.Result1 = userInfo.UserName;
                                        Model.Result2 = qyModel.FileServerUrl;
                                        Model.Result4 = userInfo;
                                    }
                                }
                                else if (Model.ErrorMsg == "")
                                {
                                    string strToken = JwtHelper.CreateJWT(corpnum, username).Token;
                                    CacheHelp.Remove(username);//登陆时清理缓存
                                    Model.Result = strToken;
                                    Model.Result1 = userInfo.UserName;
                                    Model.Result2 = qyModel.FileServerUrl;
                                    Model.Result4 = userInfo;
                                }
                                new JH_Auth_LogB().InsertLog("登录日志", context.Request.Path + "/" + Model.Action, JsonConvert.SerializeObject(Model), username, JsonConvert.SerializeObject(JsonData), 0, getIP(context));
                            }
                            #endregion
                        }
                    }
                    #endregion
                }

                if (strAction.ToUpper() == "CLEARCACHE")//上传签名
                {
                    CacheHelp.RemoveAll();
                }
            }
            else
            {
            }

            IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
            timeConverter.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
            string Result = JsonConvert.SerializeObject(Model, Newtonsoft.Json.Formatting.Indented, timeConverter).Replace("null", "\"\"");
            context.Response.Write(Result);
        }

        /// <summary>
        /// 成为开发者的第一步，验证并相应服务器的数据
        /// </summary>
        private void Auth(string token, string encodingAESKey, string corpId)
        {

            string echoString = HttpContext.Current.Request.QueryString["echoStr"];
            string signature = HttpContext.Current.Request.QueryString["msg_signature"];//企业号的 msg_signature
            string timestamp = HttpContext.Current.Request.QueryString["timestamp"];
            string nonce = HttpContext.Current.Request.QueryString["nonce"];

            string decryptEchoString = "";
            if (CheckSignature(token, signature, timestamp, nonce, corpId, encodingAESKey, echoString, ref decryptEchoString))
            {
                if (!string.IsNullOrEmpty(decryptEchoString))
                {
                    Int64 v = Convert.ToInt64(decryptEchoString);
                    HttpContext.Current.Response.Clear();
                    HttpContext.Current.Response.Write(v);
                    HttpContext.Current.Response.End();
                }
            }
        }

        #region 验证企业号签名
        /// <summary>
        /// 验证企业号签名
        /// </summary>
        /// <param name="token">企业号配置的Token</param>
        /// <param name="signature">签名内容</param>
        /// <param name="timestamp">时间戳</param>
        /// <param name="nonce">nonce参数</param>
        /// <param name="corpId">企业号ID标识</param>
        /// <param name="encodingAESKey">加密键</param>
        /// <param name="echostr">内容字符串</param>
        /// <param name="retEchostr">返回的字符串</param>
        /// <returns></returns>
        public bool CheckSignature(string token, string signature, string timestamp, string nonce, string corpId, string encodingAESKey, string echostr, ref string retEchostr)
        {
            return new MOBAPI().CheckSignature(token, signature, timestamp, nonce, corpId, encodingAESKey, echostr, ref retEchostr);
        }

        #endregion
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        public string getIP(HttpContext context)
        {
            string ipAddr = "";
            try
            {
                HttpRequest Request = context.Request;
                // 如果使用代理，获取真实IP  
                if (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != "")
                    ipAddr = Request.ServerVariables["REMOTE_ADDR"];
                else
                    ipAddr = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (ipAddr == null || ipAddr == "")
                    ipAddr = Request.UserHostAddress;
                return ipAddr;

            }
            catch (Exception ex)
            {
                return "";
            }
            return ipAddr;
        }


    }

}